package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.mapper.CourseMapper;
import com.demo.mapper.GradeMapper;
import com.demo.mapper.StudentCourseMapper;
import com.demo.mapper.StudentMapper;
import com.demo.mapper.TeacherMapper;
import com.demo.pojo.dto.ScheduleListDTO;
import com.demo.pojo.entity.Course;
import com.demo.pojo.entity.Student;
import com.demo.pojo.entity.StudentCourse;
import com.demo.pojo.entity.Teacher;
import com.demo.service.StudentUserService;
import com.demo.service.ScheduleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 学生用户服务实现类
 */
@Service
public class StudentUserServiceImpl implements StudentUserService {
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private StudentCourseMapper studentCourseMapper;
    
    @Autowired
    private CourseMapper courseMapper;
    
    @Autowired
    private TeacherMapper teacherMapper;
    
    @Autowired
    private ScheduleService scheduleService;
    
    @Autowired
    private GradeMapper gradeMapper;
    
    @Override
    public Student studentLogin(Long stuNo, String password) {
        if (stuNo == null) {
            throw new RuntimeException("学号不能为空");
        }
        
        if (password == null || password.trim().isEmpty()) {
            throw new RuntimeException("密码不能为空");
        }
        
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no", stuNo);
        Student student = studentMapper.selectOne(queryWrapper);
        
        if (student == null) {
            throw new RuntimeException("学号不存在");
        }
        
        // 验证身份证后六位
        String idCard = student.getStuIdCard();
        if (idCard == null || idCard.length() < 6) {
            throw new RuntimeException("学生身份证信息不完整");
        }
        
        String lastSixDigits = idCard.substring(idCard.length() - 6);
        if (!password.equals(lastSixDigits)) {
            throw new RuntimeException("密码错误，请输入身份证后六位");
        }
        
        return student;
    }
    
    @Override
    public Student getStudentInfo(Long studentId) {
        return studentMapper.selectById(studentId);
    }
    
    @Override
    public boolean updateStudentInfo(Student student) {
        return studentMapper.updateById(student) > 0;
    }
    
    @Override
    public List<ScheduleListDTO> getStudentSchedule(Long studentId, String semester) {
        System.out.println("=== 获取学生课表 ===");
        System.out.println("学生ID: " + studentId);
        System.out.println("学期: " + semester);
        
        // 按学生所属班级获取课表；带学期兜底
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            System.out.println("⚠️ 学生不存在");
            return new ArrayList<>();
        }
        Long clazzId = student.getClazzId();
        if (clazzId == null) {
            System.out.println("⚠️ 学生没有关联班级");
            return new ArrayList<>();
        }
        
        String usedSemester = (semester == null || semester.isBlank()) ? "advanced" : semester;
        
        // 1. 获取学生所在班级的必修课课表
        List<ScheduleListDTO> list = scheduleService.getClassSchedule(clazzId, usedSemester);
        if ((list == null || list.isEmpty()) && !"2025-1".equals(usedSemester)) {
            list = scheduleService.getClassSchedule(clazzId, "2025-1");
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        System.out.println("✅ 必修课课表: " + list.size() + " 条");
        
        // 2. 🔥 获取学生选修的选修课课表
        QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
        scWrapper.eq("student_id", studentId)
                 .eq("status", "SELECTED");  // 只查询已审核通过的选修课
        if (usedSemester != null && !usedSemester.equals("advanced")) {
            scWrapper.eq("semester", usedSemester);
        }
        
        List<StudentCourse> selectedElectives = studentCourseMapper.selectList(scWrapper);
        System.out.println("📚 已选修课程: " + selectedElectives.size() + " 门");
        
        if (!selectedElectives.isEmpty()) {
            // 获取选修课程的ID列表
            List<Long> electiveCourseIds = new ArrayList<>();
            for (StudentCourse sc : selectedElectives) {
                electiveCourseIds.add(sc.getCourseId());
            }
            
            // 查询这些选修课的排课信息
            List<ScheduleListDTO> electiveSchedules = scheduleService.getSchedulesByCourseIds(electiveCourseIds, usedSemester);
            System.out.println("✅ 选修课课表: " + electiveSchedules.size() + " 条");
            
            // 合并必修课和选修课课表
            list.addAll(electiveSchedules);
        }
        
        System.out.println("🎉 总课表: " + list.size() + " 条");
        return list;
    }
    
    @Override
    public List<ScheduleListDTO> getStudentWeekSchedule(Long studentId, String semester, Integer weekNo) {
        List<ScheduleListDTO> allSchedules = getStudentSchedule(studentId, semester);
        // 简化实现，实际需要根据周次过滤
        return allSchedules;
    }
    
    @Override
    public List<ScheduleListDTO> getStudentTodaySchedule(Long studentId, String semester, Integer weekNo, Integer dayOfWeek) {
        List<ScheduleListDTO> allSchedules = getStudentSchedule(studentId, semester);
        // 简化实现，实际需要根据星期几过滤
        return allSchedules;
    }
    
    @Override
    public List<Map<String, Object>> getAvailableCourses(Long studentId, String semester) {
        // ✅ 只查询选修课
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_type", "选修");
        List<Course> courses = courseMapper.selectList(queryWrapper);
        
        System.out.println("=== 获取可选课程（仅选修课）===");
        System.out.println("学期: " + semester);
        System.out.println("选修课数量: " + courses.size());
        
        List<Map<String, Object>> availableCourses = new ArrayList<>();
        for (Course course : courses) {
            Map<String, Object> courseInfo = new HashMap<>();
            
            // 基本课程信息
            courseInfo.put("courseId", course.getCourseId());
            courseInfo.put("courseNo", course.getCourseNo() != null ? course.getCourseNo().toString() : "");
            courseInfo.put("courseName", course.getCourseName());
            courseInfo.put("courseType", course.getCourseType());
            courseInfo.put("credit", course.getCredit());
            courseInfo.put("periodTotal", course.getPeriodTotal());
            courseInfo.put("dept", course.getDept());
            courseInfo.put("courseRemark", course.getCourseRemark());
            
            // 获取教师信息
            String teacherName = "";
            if (course.getTeacherId() != null) {
                Teacher teacher = teacherMapper.selectById(course.getTeacherId());
                if (teacher != null) {
                    teacherName = teacher.getTeName();
                }
            }
            courseInfo.put("teacherId", course.getTeacherId());
            courseInfo.put("teacherName", teacherName);
            
            // 统计已选人数（这里简化处理，设置默认值）
            // 可以根据实际需求从 student_course 表统计
            int capacity = 50; // 默认容量
            int selected = 0;  // 已选人数
            
            // 查询该课程的选课人数
            QueryWrapper<StudentCourse> scWrapper = new QueryWrapper<>();
            scWrapper.eq("course_id", course.getCourseId())
                    .eq("status", "SELECTED");
            Long count = studentCourseMapper.selectCount(scWrapper);
            selected = count != null ? count.intValue() : 0;
            
            courseInfo.put("capacity", capacity);
            courseInfo.put("selected", selected);
            courseInfo.put("remaining", capacity - selected);
            
            // 检查当前学生是否已选该课程
            QueryWrapper<StudentCourse> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("student_id", studentId)
                       .eq("course_id", course.getCourseId())
                       .eq("status", "SELECTED");
            StudentCourse studentCourse = studentCourseMapper.selectOne(checkWrapper);
            courseInfo.put("isSelected", studentCourse != null);
            
            availableCourses.add(courseInfo);
        }
        
        return availableCourses;
    }
    
    @Override
    public boolean selectCourse(Long studentId, Long courseId, String semester) {
        try {
            System.out.println("=== 学生选课（选修课）===");
            System.out.println("学生ID: " + studentId);
            System.out.println("课程ID: " + courseId);
            System.out.println("学期: " + semester);
            
            // 检查是否已选课或已申请（检查SELECTED和PENDING状态）
            QueryWrapper<StudentCourse> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("student_id", studentId)
                       .eq("course_id", courseId)
                       .in("status", "SELECTED", "PENDING");
            StudentCourse existing = studentCourseMapper.selectOne(checkWrapper);
            
            if (existing != null) {
                String status = existing.getStatus();
                if ("PENDING".equals(status)) {
                    System.out.println("⚠️ 该课程正在等待教师审核");
                } else {
                    System.out.println("⚠️ 已选过该课程");
                }
                return false;
            }
            
            // 创建新的选课记录，状态为 PENDING（待审核）
            StudentCourse studentCourse = new StudentCourse();
            studentCourse.setStudentId(studentId);
            studentCourse.setCourseId(courseId);
            studentCourse.setSemester(semester);
            studentCourse.setStatus("PENDING");  // ✅ 设置为待审核状态
            studentCourse.setSelectTime(new Date());
            studentCourse.setCreateTime(new Date());
            studentCourse.setUpdateTime(new Date());
            
            boolean success = studentCourseMapper.insert(studentCourse) > 0;
            System.out.println("选课申请提交: " + (success ? "成功（等待教师审核）" : "失败"));
            return success;
        } catch (Exception e) {
            System.err.println("❌ 选课失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean dropCourse(Long studentId, Long courseId) {
        try {
            // 查找该学生的选课记录
            QueryWrapper<StudentCourse> wrapper = new QueryWrapper<>();
            wrapper.eq("student_id", studentId)
                   .eq("course_id", courseId)
                   .eq("status", "SELECTED");
            
            StudentCourse studentCourse = studentCourseMapper.selectOne(wrapper);
            if (studentCourse != null) {
                // 直接删除选课记录
                return studentCourseMapper.deleteById(studentCourse.getId()) > 0;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public List<Map<String, Object>> getSelectedCourses(Long studentId, String semester) {
        System.out.println("=== 查询已选课程 ===");
        System.out.println("学生ID: " + studentId);
        System.out.println("学期: " + semester);
        
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                   .in("status", "SELECTED", "PENDING");  // ✅ 包含待审核和已通过的
        
        // 如果指定了学期，则按学期过滤
        if (semester != null && !semester.isEmpty()) {
            queryWrapper.eq("semester", semester);
        }
        
        List<StudentCourse> studentCourses = studentCourseMapper.selectList(queryWrapper);
        System.out.println("找到选课记录: " + studentCourses.size() + " 条");
        
        List<Map<String, Object>> selectedCourses = new ArrayList<>();
        for (StudentCourse sc : studentCourses) {
            Course course = courseMapper.selectById(sc.getCourseId());
            if (course != null) {
                Map<String, Object> courseInfo = new HashMap<>();
                
                // 学生选课信息
                courseInfo.put("studentCourseId", sc.getId());
                courseInfo.put("selectTime", sc.getSelectTime());
                courseInfo.put("status", sc.getStatus());  // ✅ 添加审核状态：PENDING/SELECTED
                
                // 完整的课程信息（与可选课程保持一致）
                courseInfo.put("courseId", course.getCourseId());
                courseInfo.put("courseNo", course.getCourseNo() != null ? course.getCourseNo().toString() : "");
                courseInfo.put("courseName", course.getCourseName());
                courseInfo.put("courseType", course.getCourseType());
                courseInfo.put("credit", course.getCredit());
                courseInfo.put("periodTotal", course.getPeriodTotal());
                courseInfo.put("dept", course.getDept());
                courseInfo.put("courseRemark", course.getCourseRemark());
                
                // 获取教师信息
                String teacherName = "";
                if (course.getTeacherId() != null) {
                    Teacher teacher = teacherMapper.selectById(course.getTeacherId());
                    if (teacher != null) {
                        teacherName = teacher.getTeName();
                    }
                }
                courseInfo.put("teacherId", course.getTeacherId());
                courseInfo.put("teacherName", teacherName);
                
                selectedCourses.add(courseInfo);
            }
        }
        
        return selectedCourses;
    }
    
    @Override
    public List<Map<String, Object>> getStudentGrades(Long studentId, String semester) {
        // 从grade表查询学生成绩（教师录入的成绩）
        List<Map<String, Object>> grades = gradeMapper.getStudentGradesWithDetails(studentId, semester);
        return grades != null ? grades : new ArrayList<>();
    }
    
    @Override
    public Map<String, Object> getStudentCreditStats(Long studentId) {
        QueryWrapper<StudentCourse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId)
                   .eq("status", "COMPLETED");
        
        List<StudentCourse> completedCourses = studentCourseMapper.selectList(queryWrapper);
        
        BigDecimal totalCredits = BigDecimal.ZERO;
        for (StudentCourse sc : completedCourses) {
            if (sc.getCredit() != null) {
                totalCredits = totalCredits.add(sc.getCredit());
            }
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalCredits", totalCredits);
        stats.put("completedCourses", completedCourses.size());
        
        return stats;
    }
    
    @Override
    public List<Map<String, Object>> getStudentCourseReminders(Long studentId, String semester) {
        List<ScheduleListDTO> schedules = getStudentSchedule(studentId, semester);
        List<Map<String, Object>> reminders = new ArrayList<>();
        Date now = new Date();
        for (ScheduleListDTO s : schedules) {
            Map<String, Object> item = new HashMap<>();
            item.put("courseName", s.getCourseName());
            item.put("classroomName", s.getClassroomName());
            item.put("teacherName", s.getTeacherName());
            item.put("weekNo", s.getWeekNo());
            item.put("dayOfWeek", s.getDayOfWeek());
            item.put("periodNo", s.getPeriodNo());
            item.put("createTime", now);
            reminders.add(item);
        }
        return reminders;
    }

    @Override
    public Long resolveStudentId(String studentIdOrNo, String stuNo) {
        if (stuNo != null && !stuNo.isBlank() && stuNo.chars().allMatch(Character::isDigit)) {
            QueryWrapper<Student> byNo = new QueryWrapper<>();
            byNo.eq("stu_no", Long.parseLong(stuNo));
            Student s = studentMapper.selectOne(byNo);
            return s == null ? null : Long.valueOf(s.getStudentId());
        }
        if (studentIdOrNo == null || studentIdOrNo.isBlank()) {
            return null;
        }
        boolean numeric = studentIdOrNo.chars().allMatch(Character::isDigit);
        if (numeric) {
            try {
                long num = Long.parseLong(studentIdOrNo);
                Student byId = studentMapper.selectById(num);
                if (byId != null) {
                    return Long.valueOf(byId.getStudentId());
                }
                QueryWrapper<Student> byNo = new QueryWrapper<>();
                byNo.eq("stu_no", num);
                Student s = studentMapper.selectOne(byNo);
                return s == null ? null : Long.valueOf(s.getStudentId());
            } catch (NumberFormatException ignore) {
                return null;
            }
        }
        return null;
    }
}
